package com.shenhan.esactionjd.service.impl;

import com.alibaba.fastjson.JSON;
import com.shenhan.esactionjd.pojo.Content;
import com.shenhan.esactionjd.service.ContentService;
import com.shenhan.esactionjd.utils.HtmlParseUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author shenhan
 * @create 2020/5/21 10:57
 * @description
 */
@Service
@Slf4j
public class ContentServiceImpl implements ContentService {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    /**
     * 爬取页面 放入es
     *
     * @param keywords 关键字
     * @return 成功失败
     */
    @Override
    public boolean parseContent(String keywords) {
        try {
            List<Content> contents = HtmlParseUtil.parseJD(keywords);
            BulkRequest bulkRequest = new BulkRequest();
            bulkRequest.timeout("2m");
            for (Content content : contents) {
                bulkRequest.add(new IndexRequest("jd_goods").source(JSON.toJSONString(content), XContentType.JSON));
            }
            final BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            return !bulk.hasFailures();
        } catch (Exception e) {
            log.error("爬取数据失败" + e.getMessage());
            return false;
        }
    }

    @Override
    public List<Map<String, Object>> searchPage(String keyword, int pageNo, int pageSize) {
        if (pageNo <= 1) {
            pageNo = 1;
        }
        final SearchRequest searchRequest = new SearchRequest("jd_goods");
        final SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);
        // 精准匹配
        final TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title").preTags("<span style='color:red'>")
                .postTags("</span>").requireFieldMatch(false);
        sourceBuilder.highlighter(highlightBuilder);

        // 执行搜索
        searchRequest.source(sourceBuilder);
        final SearchResponse response;
        final ArrayList<Map<String, Object>> list = new ArrayList<>();
        try {
            response = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error(e.getMessage());
            return Optional.of(list).get();
        }
        for (SearchHit documentFields : response.getHits().getHits()) {
            final Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
            final HighlightField title = highlightFields.get("title");
            final Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            if (title != null) {
                final Text[] fragments = title.fragments();
                StringBuilder name = new StringBuilder();
                for (Text text : fragments) {
                    name.append(text);
                }
                sourceAsMap.put("title", name.toString());
            }
            list.add(sourceAsMap);
        }
        return list;
    }
}
